import React, { useState, useEffect } from 'react';
import { useModel } from 'umi';

import { message, Drawer, Form, Input, Button, Radio, InputNumber, Select, Spin } from 'antd';
import { formatDict } from '@/utils';
import { addField, upadataField, getDetail } from '../api';

const { Option } = Select;

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type, currentIndex = 0, unitid } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const { initialState } = useModel('@@initialState');
  const datasource_type = formatDict(initialState?.dictData || [], 'datasource_type');

  // 详情
  const getDetailData = () => {
    const payload = {
      id: data.id,
    };
    setLoading(true);
    getDetail(payload).then(res => {
      setLoading(false);
      if (res.code === 0) {
        form.setFieldsValue({ ...res.data, ...data });
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  useEffect(() => {
    if (type === 'updata' && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }
    form.setFieldsValue({ status: 0, postSort: currentIndex });
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);
    upadataField({ ...values, id: data.id, unitid: unitid }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);

    addField({ ...values, unitid: unitid }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      if (type === 'updata') updataData(values);
      if (type === 'add') addData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <Drawer
      getContainer={false}
      width={640}
      title={type === 'updata' ? '修改' : '添加'}
      visible={visible}
      onClose={modelClose}
      maskClosable={false}
      footer={
        <div
          style={{
            textAlign: 'right',
          }}
        >
          <Button onClick={modelClose} style={{ marginRight: 10 }}>
            取消
          </Button>
          <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
            保存
          </Button>
        </div>
      }
    >
      <Spin spinning={loading}>
        <Form {...formItemLayout} name="control-ref" form={form}>
          <Form.Item label="源名称" name="name" rules={[{ required: true }]}>
            <Input maxLength={120} />
          </Form.Item>

          {/* <Form.Item label='数据源简称' name='abbreviation' rules={[{ required: true }]}>
            <Input maxLength={20} />
          </Form.Item> */}

          <Form.Item label="数据库驱动" name="dbdriver" rules={[{ required: true }]}>
            <Select>
              {datasource_type.map(item => {
                return (
                  <Option key={item.dictValue} value={item.dictLabel}>
                    {item.dictValue}
                  </Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item name="state" label="数据源状态">
            <Radio.Group>
              <Radio value="0">禁用</Radio>
              <Radio value="1">激活</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="数据库地址" name="dburl" rules={[{ required: true }]}>
            <Input maxLength={120} />
          </Form.Item>
          <Form.Item label="数据库名称" name="dbname" rules={[{ required: true }]}>
            <Input maxLength={120} />
          </Form.Item>
          <Form.Item label="数据库用户名" name="dbuser" rules={[{ required: true }]}>
            <Input maxLength={120} />
          </Form.Item>
          <Form.Item label="数据库密码" name="dbpass" rules={[{ required: true }]}>
            <Input maxLength={120} />
          </Form.Item>
          <Form.Item label="备注" name="memo">
            <Input.TextArea maxLength={200} allowClear />
          </Form.Item>
        </Form>
      </Spin>
    </Drawer>
  );
};

export default UpdateForm;
